<template>
    <div class="app-container">
        <el-tabs type="border-card" v-model="activeName">
            <el-tab-pane label="基本设置" name="first">
                <el-col :span="20" :offset="2" >
                    <el-form :model="basicInfo" ref="basicForm" :rules="baseRule" label-width="100px">
                        <el-form-item label="系统图标:"  prop="loginUrl" >
                            <div class="iconList">
                                <div class="content">
                                    <el-upload
                                        class="avatar-uploader"
                                        accept=".jpg,.png"
                                        :before-upload="beforeAvatarUpload"
                                        :action="uploadFileUrl"
                                        :show-file-list="false"
                                        :on-success="(response, file, fileList) =>handleUploadSuccess(response, file, fileList,'loginUrl')"
                                        :headers="{'Authorization':`Bearer ${token}`}">
                                        <img v-if="basicInfo.loginUrl" :src="basicInfo.loginUrl" class="avatar">
                                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                    </el-upload>
                                    <span>登录图标</span>
                                </div>
                                 <div class="content" style="margin-left:20px">
                                    <el-upload
                                        class="avatar-uploader"
                                        accept=".jpg,.png"
                                        :before-upload="beforeAvatarUpload"
                                        :action="uploadFileUrl"
                                        :show-file-list="false"
                                        :on-success="(response, file, fileList) =>handleUploadSuccess(response, file, fileList,'navigationUrl')"
                                        :headers="{'Authorization':`Bearer ${token}`}">
                                        <img v-if="basicInfo.navigationUrl" :src="basicInfo.navigationUrl" class="avatar">
                                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                    </el-upload>
                                    <span>导航图标</span>
                                </div>
                                 <div class="content" style="margin-left:20px"> 
                                    <el-upload
                                        class="avatar-uploader"
                                        accept=".jpg,.png"
                                        :before-upload="beforeAvatarUpload"
                                        :action="uploadFileUrl"
                                        :show-file-list="false"
                                        :on-success="(response, file, fileList) =>handleUploadSuccess(response, file, fileList,'browserUrl')"
                                        :headers="{'Authorization':`Bearer ${token}`}">
                                        <img v-if="basicInfo.browserUrl" :src="basicInfo.browserUrl" class="avatar">
                                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                    </el-upload>
                                    <span>浏览器图标</span>
                                </div>
                                 <!-- <div class="content" style="margin-left:20px">
                                    <el-upload
                                        class="avatar-uploader"
                                        :action="uploadFileUrl"
                                        :show-file-list="false"
                                         :on-success="(response, file, fileList) =>handleUploadSuccess(response, file, fileList,'appUrl')"
                                        :headers="{'Authorization':`Bearer ${token}`}">
                                        <img v-if="basicInfo.appUrl" :src="basicInfo.appUrl" class="avatar">
                                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                    </el-upload>
                                    <span>APP图标</span>
                                </div> -->
                            </div>
                        </el-form-item>
                        <el-form-item label="登录名称:" prop="loginName">
                             <el-input  v-model="basicInfo.loginName" placeholder="请输入登录名称" maxlength="50"/>
                        </el-form-item>
                         <el-form-item label="导航名称:" prop="navigationName">
                             <el-input v-model="basicInfo.navigationName" placeholder="请输入导航名称" maxlength="50"/>
                        </el-form-item>
                         <el-form-item label="版权信息:" prop="copyrightInfo">
                             <el-input  v-model="basicInfo.copyrightInfo" placeholder="请输入版权信息" maxlength="50"/>
                        </el-form-item>
                        <!-- <el-form-item label="系统描述:" prop="systemSpecifi">
                             <el-input type="textarea" v-model="basicInfo.systemSpecifi" placeholder="请输入系统描述" />
                        </el-form-item> -->
                        <el-form-item>
                            <el-button type="primary" @click="submitBaseForm" v-disPrevent>保存</el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-tab-pane>
            <el-tab-pane label="安全设置" name="second">
                 <el-col :span="20" :offset="2" >
                    <el-form :model="safeForm" ref="safeForm" :rules="safeRule" label-width="120px">
                        <el-form-item label="登录方式:"  prop="loginMethod" :class="safeForm.loginMethod == 1 ?'marginfive': 'marginten'">
                            <el-select placeholder="请选择" size="small" v-model="safeForm.loginMethod">
                                <el-option label="单一登录" :value="1"></el-option>
                                <el-option label="同时登录" :value="0"></el-option>
                            </el-select>
                        </el-form-item>  
                        <el-form-item  prop="loginOrder" v-if="safeForm.loginMethod == 1">
                            <el-radio-group v-model="safeForm.loginOrder">
                                <el-radio :label="0">后登录踢出先登录</el-radio>
                                <el-radio :label="1">已登录禁止再登录</el-radio>
                            </el-radio-group>
                        </el-form-item>  
                         <el-form-item label="超时登录:" prop="loginTimeOutPeriod">
                            <el-input-number v-model='safeForm.loginTimeOutPeriod' :min="0"/> 分钟
                        </el-form-item> 
                        <el-form-item label="密码错误次数:" prop="passwordErrorNumber" style="margin-bottom: 5px">
                            <el-input-number v-model='safeForm.passwordErrorNumber' :min="0"/> 次
                            <div style="font-size: 12px;margin-top: -5px;">输入密码错误将用户锁定，设置3以下值表示不启动该功能</div>
                        </el-form-item> 
                         <el-form-item  prop="LockOrDelay">
                             <el-radio-group v-model="safeForm.LockOrDelay">
                                <el-radio :label="0">账号锁定</el-radio>
                                <el-radio :label="1">延时登录</el-radio>
                            </el-radio-group>
                        </el-form-item> 
                         <el-form-item label="延迟时间:" prop="delayTime" v-if="safeForm.LockOrDelay === 1">
                            <el-input-number v-model='safeForm.delayTime' :min="0"/> 分钟
                        </el-form-item> 
                        <el-form-item label="登录验证码:" prop="openVerificationCode">
                            <el-switch v-model="safeForm.openVerificationCode" active-value="1" inactive-value="0"></el-switch>
                        </el-form-item> 
                        <el-form-item label="登录提示语:" prop="openLoginPrompt">
                            <el-switch v-model="safeForm.openLoginPrompt" active-value="1" inactive-value="0"></el-switch>
                            <div v-if="safeForm.openLoginPrompt === '1'">
                                <el-card class="box-card">
                                    <div slot="header" class="clearfix">
                                        <span>上次登录信息提示</span>
                                        <i class="el-icon-close" style="float: right; padding: 3px 0,line-height: 36px" ></i>
                                    </div>
                                    <div class="text item">
                                       <div>时间: 2022-8-26 12:22</div>
                                       <div>地点：西安</div>
                                       <div>IP：255.255.0.0</div>
                                    </div>
                                </el-card>
                            </div>
                        </el-form-item> 
                        <el-form-item label="白名单验证:" prop="openWhiteList">
                            <el-switch v-model="safeForm.openWhiteList" active-value="1" inactive-value="0"></el-switch>
                        </el-form-item>
                        <el-form-item label="白名单设置:" prop="whiteList" v-if="safeForm.openWhiteList === '1'">
                            <el-input type="textarea" v-model="basicInfo.whiteList" placeholder="请输入" />
                            <div style="font-size: 12px;margin-top: -5px">多个IP设置，用英文逗号隔开，如192.168.0.1,192.168.0.2</div>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="submitSafeForm" v-disPrevent>保存</el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-tab-pane>
            <el-tab-pane label="第三方设置" name="third">
                 <el-tabs tab-position="left">
                    <el-tab-pane label="阿里短信">
                        <el-col :span="20" :offset="1" >
                            <el-form :model="aliSmsInfo" ref="aliSmsForm" :rules="aliSmsRule" label-width="140px">
                                <el-form-item label="AccessKey ID:"  prop="aliAccessKeyID" >
                                    <el-input  v-model="aliSmsInfo.aliAccessKeyID" placeholder="请输入AccessKey ID" />
                                </el-form-item>
                                <el-form-item label="AccessKey Secret:"  prop="aliAccessKeySecret">
                                    <el-input  v-model="aliSmsInfo.aliAccessKeySecret" placeholder="请输入AccessKey Secret"  type="password" show-password/>
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="submitaliSmsForm" v-disPrevent>保存</el-button>
                                </el-form-item>
                            </el-form>
                        </el-col>
                    </el-tab-pane>
                    <el-tab-pane label="腾讯短信">
                        <el-col :span="20" :offset="1" >
                            <el-form :model="tencentInfo" ref="tencentForm" :rules="tencentRule" label-width="140px">
                                <el-form-item label="SecretId:"  prop="tencentSecretId" >
                                    <el-input  v-model="tencentInfo.tencentSecretId" placeholder="请输入SecretId" />
                                </el-form-item>
                                <el-form-item label="SecretKey:"  prop="tencentSecretKey" >
                                    <el-input  v-model="tencentInfo.tencentSecretKey" placeholder="请输入SecretKey" type="password" show-password/>
                                </el-form-item>
                                <el-form-item label="SDK AppID:"  prop="tencentSDKAppID" >
                                    <el-input  v-model="tencentInfo.tencentSDKAppID" placeholder="请输入SDK AppID" />
                                </el-form-item>
                                <el-form-item label="App Key:"  prop="tencentAppKEy" >
                                    <el-input  v-model="tencentInfo.tencentAppKEy" placeholder="请输入App Key" type="password" show-password/>
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="submitTencentForm" v-disPrevent>保存</el-button>
                                </el-form-item>
                            </el-form>
                        </el-col>
                    </el-tab-pane>
                    <el-tab-pane label="电子邮箱">
                         <el-alert title="注意：系统邮件设置成功后所有邮件会由此邮箱发出" type="warning" :closable="false" show-icon style="margin-bottom: 20px;"></el-alert>
                         <el-form :model="emailInfo" ref="emailForm" label-width="140px" :rules="emailRule">
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="POP3服务:"  prop="emailPOP3Servic" :rules="{ required: true, trigger: ['blur', 'change'], message: '请输入' }">
                                        <el-input  v-model="emailInfo.emailPOP3Servic" placeholder="请输入POP3服务" />
                                    </el-form-item>
                                    <el-form-item label="POP3端口:" prop="emailPOP3Port" :rules="{ required: true, trigger: ['blur', 'change'], message: '请输入' }">
                                        <el-input-number v-model='emailInfo.emailPOP3Port' />
                                    </el-form-item> 
                                    <el-form-item label="显示名称:"  prop="emailName" :rules="{ required: true, trigger: ['blur', 'change'], message: '请输入名称' }">
                                        <el-input  v-model="emailInfo.emailName" placeholder="请输入名称" />
                                    </el-form-item>
                                    <el-form-item label="邮箱账户:"  prop="emailAccount" 
                                        :rules="{ required: true, trigger: ['blur', 'change'], message: '请输入邮箱账户' }"
                                    >
                                        <el-input  v-model="emailInfo.emailAccount" placeholder="请输入邮箱账户" />
                                    </el-form-item>
                                    <el-form-item label="邮箱密码:"  prop="emailPassword" 
                                        :rules="{ required: true, trigger: ['blur', 'change'], message: '请输入邮箱密码' }"
                                    >
                                        <el-input  v-model="emailInfo.emailPassword" placeholder="请输入邮箱密码"  type="password" show-password>
                                            <template slot="append">
                                                <el-button @click="testLink" :disabled='testFlag'>测试连接</el-button>
                                            </template>
                                        </el-input>
                                    </el-form-item>
                                    <el-form-item>
                                        <el-button type="primary" @click="submitEmailForm" v-disPrevent>保存</el-button>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                     <el-form-item label="SMTP服务:"  prop="emailSMTPService" :rules="{ required: true, trigger: ['blur', 'change'], message: '请输入SMTP服务' }">
                                        <el-input  v-model="emailInfo.emailSMTPService" placeholder="请输入SMTP服务" />
                                    </el-form-item>
                                    <el-form-item label="SMTP端口:" prop="emailSMTPPort" :rules="{ required: true, trigger: ['blur', 'change'], message: '请输入' }">
                                        <el-input-number v-model='emailInfo.emailSMTPPort' />
                                    </el-form-item> 
                                </el-col>
                            </el-row>
                         </el-form>
                    </el-tab-pane>
                </el-tabs>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>
<script>
import { getConfListByconfKey, update, testEmail} from "@/api/system/systemConfig";
import {getAccessToken, encryption} from '@/utils/auth'
import { disPrevent } from '@/utils/disPrevent'

export default {
    data() {
        return {
            uploadPng:true,
            testFlag: false,
            token: '', //接口请求token
            activeName: 'first',
            basicInfo: {
                loginUrl: '',
                navigationUrl: '',
                browserUrl: '',
                appUrl: ''
            },
            uploadFileUrl: process.env.VUE_APP_BASE_API + "/admin-api/infra/file/uploadimage", // 请求地址
            baseRule: {
                loginUrl: [
                     {
                        required: true,
                        validator: (rules, value, cb) => {
                            let { navigationUrl, browserUrl, appUrl} = this.basicInfo;
                            if (!value || !navigationUrl || !browserUrl || !appUrl) {
                                return cb(new Error("请上传系统图标"));
                            }
                            return cb();
                        },
                        trigger: "change"
                    }
                ],
                loginName: {required: true, message: '请输入登录名称',trigger: 'blur'},
                navigationName: {required: true, message: '请输入导航名称',trigger: 'blur'},
                copyrightInfo: {required: true, message: '请输入版权信息',trigger: 'blur'},
                systemSpecifi: {required: true, message: '请输入系统描述',trigger: 'blur'},
            },
            safeForm: {
                loginMethod: 0,
                loginOrder: 0,
                LockOrDelay: 0,
            },
            safeRule: {
                loginMethod: {required: true, message: '请选择',trigger: 'change'},
                loginTimeOutPeriod: {required: true, message: '请输入',trigger: 'blur'},
                passwordErrorNumber: {required: true, message: '请输入',trigger: 'blur'},
                delayTime: {required: true, message: '请输入',trigger: 'blur'},
            },
            aliSmsInfo: {

            },
            aliSmsRule: {
                aliAccessKeyID: {required: true, message: '请输入AccessKey ID',trigger: 'blur'},
                aliAccessKeySecret: {required: true, message: '请输入AccessKey Secret',trigger: 'blur'},
            },
            tencentInfo: {},
            tencentRule: {
                tencentSecretId: {required: true, message: '请输入SecretId',trigger: 'blur'},
                tencentSecretKey: {required: true, message: '请输入SecretKey',trigger: 'blur'},
                tencentSDKAppID: {required: true, message: '请输入SDK AppID',trigger: 'blur'},
                tencentAppKEy: {required: true, message: '请输入App Key',trigger: 'blur'},
            },
            emailInfo: {},
            emailRule: {
                emailAccount: [
                      {
                        type: "email",
                        message: "'请输入正确的邮箱账户",
                        trigger: ["blur", "change"]
                    }
                ]
            }
        }
    },
    mounted() {
      this.token =  getAccessToken()
    },
    created() {
        this.getConfList()
    },
    methods: {
      //限制上传图片格式
      beforeAvatarUpload(file) {
        let fileExtName = file.name.substring(file.name.lastIndexOf('.') + 1)
        if(
            fileExtName === 'jpg' || fileExtName === 'png'
        ){
          //进行上传成功的一些操作;
            // console.log('file',file);
            this.uploadPng = true
        }else{
            // 提醒只能上传的文件类型
            this.$message.warning('只能上传.jpg、.png类型的文件！')
            this.uploadPng = false
            return
        }
      },
        getConfList() {
            getConfListByconfKey().then(res => {
                if(res.code === 0){
                    this.basicInfo = JSON.parse(res.data.filter((_) => _.confKey == "system_base")[0].confValue)  //基本设置
                    this.safeForm = JSON.parse(res.data.filter((_) => _.confKey == "system_safe")[0].confValue)  //安全设置
                    this.aliSmsInfo = JSON.parse(res.data.filter((_) => _.confKey == "system_ali_sms")[0].confValue)  //阿里短信
                    this.tencentInfo = JSON.parse(res.data.filter((_) => _.confKey == "system_tencent_sms")[0].confValue)  //腾讯短信
                    this.emailInfo = JSON.parse(res.data.filter((_) => _.confKey == "system_email")[0].confValue)  //电子邮箱
                }
            })
        },
          // 上传成功回调
        handleUploadSuccess(response, file, fileList,title) {
            if(response.code === 0){
                this.basicInfo[title] = response.data
            }
        },
        submitBaseForm() {
            this.$refs.basicForm.validate(valid => {
                if (!valid) return
                if(!this.uploadPng){
                  this.$message.warning('只能上传.jpg、.png类型的文件！')
                }else{
                    let data = {
                      type: '1',
                      id: 2,
                      confKey: 'system_base',
                      description: '系统基本设置',
                      confValue: JSON.stringify(this.basicInfo)
                    }
                    update(data).then((res) => {
                        if(res.code === 0){
                            this.$message.success('保存成功')
                        }
                    })
                }
                 
            })
        },
        submitSafeForm() {
            this.$refs.safeForm.validate(valid => {
                if (!valid) return
                 let data = {
                    type: '1',
                    id: 3,
                    confKey: 'system_safe',
                    description: '安全设置',
                    confValue: JSON.stringify(this.safeForm)
                }
                update(data).then((res) => {
                    if(res.code === 0){
                        this.$message.success('保存成功')
                    }
                })
            })
        },
        submitaliSmsForm() {
            this.$refs.aliSmsForm.validate(valid => {
                if (!valid) return
                const dataInfo = {
                    aliAccessKeyID: this.aliSmsInfo.aliAccessKeyID,
                    aliAccessKeySecret: encryption(this.aliSmsInfo.aliAccessKeySecret)
                }
                 let data = {
                    type: '1',
                    id: 4,
                    confKey: 'system_ali_sms',
                    description: '阿里短信',
                    confValue: JSON.stringify(dataInfo)
                }
                update(data).then((res) => {
                    if(res.code === 0){
                        this.$message.success('保存成功')
                    }
                })
            })
        },
        submitTencentForm() {
            this.$refs.tencentForm.validate(valid => {
                if (!valid) return
                const dataInfo = {
                    tencentSecretId: this.tencentInfo.tencentSecretId,
                    tencentSDKAppID: this.tencentInfo.tencentSDKAppID,
                    tencentSecretKey: encryption(this.tencentInfo.tencentSecretKey),
                    tencentAppKEy: encryption(this.tencentInfo.tencentAppKEy),
                }
                 let data = {
                    type: '1',
                    id: 5,
                    confKey: 'system_tencent_sms',
                    description: '腾讯短信',
                    confValue: JSON.stringify(dataInfo)
                }
                update(data).then((res) => {
                    if(res.code === 0){
                        this.$message.success('保存成功')
                    }
                })
            })
        },
        submitEmailForm() {
            this.$refs.emailForm.validate(valid => {
                if (!valid) return
                const dataInfo = {
                    emailPassword:  encryption(this.emailInfo.emailPassword),
                    emailPOP3Servic: this.emailInfo.emailPOP3Servic,
                    emailName: this.emailInfo.emailName,
                    emailSMTPService: this.emailInfo.emailSMTPService,
                    emailSMTPPort: this.emailInfo.emailSMTPPort,
                    emailPOP3Port: this.emailInfo.emailPOP3Port,
                    emailAccount: this.emailInfo.emailAccount,
                }
                 let data = {
                    type: '1',
                    id: 6,
                    confKey: 'system_email',
                    description: '电子邮箱配置',
                    confValue: JSON.stringify(dataInfo)
                }
                update(data).then((res) => {
                    if(res.code === 0){
                        this.$message.success('保存成功')
                    }
                })
            })
        },
        testLink() {
            this.testFlag = true
            const data = {
                emailPassword:  encryption(this.emailInfo.emailPassword),
                emailPOP3Servic: this.emailInfo.emailPOP3Servic,
                emailName: this.emailInfo.emailName,
                emailSMTPService: this.emailInfo.emailSMTPService,
                emailSMTPPort: this.emailInfo.emailSMTPPort,
                emailPOP3Port: this.emailInfo.emailPOP3Port,
                emailAccount: this.emailInfo.emailAccount,
            }
            testEmail(data).then((res) => {
                if(res.code == 0){
                    if(res.data){
                        this.testFlag = false
                        this.$message.success('测试连接成功')
                    }else{
                        this.testFlag = false
                        this.$message.error('测试连接失败')
                    }
                }else{
                    this.testFlag = false 
                }
            })
        }
    }
}
</script>

<style lang="scss">
.iconList{
    display: flex;
    .content{
        text-align: center;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        overflow: hidden;
    }
}
.marginfive{
    margin-bottom: 5px;
}
.marginten{
    margin-bottom: 22px;
}
 .el-upload {
    cursor: pointer;
    position: relative;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
    .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 350px;
  }
</style> 